# DMZ环境Oracle连接问题终极解决方案
# 针对已使用Oracle.ManagedDataAccess.Core但仍有连接问题的情况

Write-Host "=== DMZ环境Oracle连接问题终极解决方案 ===" -ForegroundColor Green
Write-Host "检测到项目已使用Oracle.ManagedDataAccess.Core 23.6.0" -ForegroundColor Yellow
Write-Host "本脚本将诊断并解决DMZ环境下的连接问题" -ForegroundColor Yellow
Write-Host ""

# 检查当前目录
$currentDir = Get-Location
Write-Host "当前目录: $currentDir" -ForegroundColor Cyan

# 第一步：网络连通性诊断
Write-Host "
=== 第一步：网络连通性诊断 ===" -ForegroundColor Cyan

# 从配置文件读取Oracle连接信息
$appsettingsFile = "appsettings.json"
if (Test-Path $appsettingsFile) {
    try {
        $config = Get-Content $appsettingsFile -Raw | ConvertFrom-Json
        $oracleConnString = $null
        
        # 查找Oracle连接字符串
        if ($config.ConnectionStrings) {
            foreach ($connName in $config.ConnectionStrings.PSObject.Properties.Name) {
                $connString = $config.ConnectionStrings.$connName
                if ($connString -match "Data Source=([^;]+)" -or $connString -match "oracle|ORACLE") {
                    $oracleConnString = $connString
                    Write-Host "找到Oracle连接字符串: $connName" -ForegroundColor Green
                    break
                }
            }
        }
        
        if ($oracleConnString) {
            # 解析连接字符串中的主机和端口
            if ($oracleConnString -match "Data Source=([^:]+):?(\d+)?[/:]?([^;]+)?") {
                $oracleHost = $matches[1]
                $oraclePort = if ($matches[2]) { $matches[2] } else { "1521" }
                $oracleService = $matches[3]
                
                Write-Host "Oracle主机: $oracleHost" -ForegroundColor White
                Write-Host "Oracle端口: $oraclePort" -ForegroundColor White
                Write-Host "Oracle服务: $oracleService" -ForegroundColor White
                
                # 测试网络连通性
                Write-Host "\n测试网络连通性..." -ForegroundColor Yellow
                try {
                    $tcpTest = Test-NetConnection -ComputerName $oracleHost -Port $oraclePort -WarningAction SilentlyContinue
                    if ($tcpTest.TcpTestSucceeded) {
                        Write-Host "✓ 网络连通性正常" -ForegroundColor Green
                    } else {
                        Write-Host "✗ 网络连通性失败" -ForegroundColor Red
                        Write-Host "请检查防火墙和网络配置" -ForegroundColor Yellow
                    }
                } catch {
                    Write-Host "网络测试失败: $_" -ForegroundColor Red
                }
            }
        } else {
            Write-Host "未找到Oracle连接字符串" -ForegroundColor Yellow
        }
    } catch {
        Write-Host "解析配置文件失败: $_" -ForegroundColor Red
    }
} else {
    Write-Host "未找到appsettings.json文件" -ForegroundColor Yellow
}

# 第二步：创建增强的连接字符串
Write-Host "
=== 第二步：生成DMZ优化连接字符串 ===" -ForegroundColor Cyan

# 提示用户输入连接信息
Write-Host "请输入Oracle连接信息（如果当前配置有问题）:" -ForegroundColor Yellow
$hostInput = Read-Host "Oracle主机IP (回车跳过)"
$portInput = Read-Host "Oracle端口 (默认1521，回车跳过)"
$serviceInput = Read-Host "Oracle服务名 (回车跳过)"
$userInput = Read-Host "用户名 (回车跳过)"
$passwordInput = Read-Host "密码 (回车跳过)" -AsSecureString

if ($hostInput -and $serviceInput -and $userInput) {
    $port = if ($portInput) { $portInput } else { "1521" }
    $password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($passwordInput))
    
    # 生成DMZ环境优化的连接字符串
    $optimizedConnString = "Data Source=$hostInput`:$port/$serviceInput;User Id=$userInput;Password=$password;" +
                          "Connection Timeout=120;" +
                          "Command Timeout=300;" +
                          "Pooling=true;" +
                          "Min Pool Size=1;" +
                          "Max Pool Size=50;" +
                          "Connection Lifetime=600;" +
                          "Incr Pool Size=2;" +
                          "Decr Pool Size=1;" +
                          "Validate Connection=true;" +
                          "Self Tuning=true;" +
                          "Statement Cache Size=50;" +
                          "Load Balancing=false;" +
                          "HA Events=true;" +
                          "Connection Pool Timeout=30;"
    
    Write-Host "\n生成的DMZ优化连接字符串:" -ForegroundColor Green
    $maskedConnString = $optimizedConnString -replace "Password=[^;]+", "Password=***"
    Write-Host $maskedConnString -ForegroundColor White
    
    # 更新配置文件
    if (Test-Path $appsettingsFile) {
        $updateConfig = Read-Host "\n是否更新appsettings.json? (y/n)"
        if ($updateConfig -eq 'y' -or $updateConfig -eq 'Y') {
            try {
                # 备份原文件
                $backupFile = "$appsettingsFile.backup.$(Get-Date -Format 'yyyyMMdd-HHmmss')"
                Copy-Item $appsettingsFile $backupFile
                Write-Host "已备份原配置: $backupFile" -ForegroundColor Yellow
                
                # 更新配置
                $config = Get-Content $appsettingsFile -Raw | ConvertFrom-Json
                if (-not $config.ConnectionStrings) {
                    $config | Add-Member -Type NoteProperty -Name "ConnectionStrings" -Value @{}
                }
                $config.ConnectionStrings.OracleConnection = $optimizedConnString
                
                $config | ConvertTo-Json -Depth 10 | Set-Content $appsettingsFile -Encoding UTF8
                Write-Host "✓ 已更新配置文件" -ForegroundColor Green
            } catch {
                Write-Host "更新配置文件失败: $_" -ForegroundColor Red
            }
        }
    }
}

# 第三步：创建高级连接测试工具
Write-Host "
=== 第三步：创建高级连接测试工具 ===" -ForegroundColor Cyan

$advancedTestContent = @'
using Oracle.ManagedDataAccess.Client;
using Microsoft.Extensions.Configuration;
using System;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Net.NetworkInformation;
using System.Net.Sockets;

namespace Lzfy_His_Service
{
    /// <summary>
    /// DMZ环境Oracle连接高级诊断工具
    /// </summary>
    public class AdvancedOracleConnectionDiagnostic
    {
        private readonly IConfiguration _configuration;
        
        public AdvancedOracleConnectionDiagnostic(IConfiguration configuration)
        {
            _configuration = configuration;
        }
        
        /// <summary>
        /// 全面诊断Oracle连接问题
        /// </summary>
        public async Task<bool> ComprehensiveDiagnosticAsync(string connectionName = "OracleConnection")
        {
            Console.WriteLine("=== DMZ环境Oracle连接全面诊断 ===");
            Console.WriteLine($"诊断时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
            Console.WriteLine($"环境信息: {Environment.OSVersion}");
            Console.WriteLine($".NET版本: {Environment.Version}");
            Console.WriteLine();
            
            var connectionString = _configuration.GetConnectionString(connectionName);
            if (string.IsNullOrEmpty(connectionString))
            {
                Console.WriteLine($"❌ 错误: 未找到连接字符串 '{connectionName}'");
                return false;
            }
            
            // 1. 解析连接字符串
            var connInfo = ParseConnectionString(connectionString);
            Console.WriteLine("=== 1. 连接字符串分析 ===");
            Console.WriteLine($"主机: {connInfo.Host}");
            Console.WriteLine($"端口: {connInfo.Port}");
            Console.WriteLine($"服务: {connInfo.Service}");
            Console.WriteLine($"用户: {connInfo.User}");
            Console.WriteLine($"连接超时: {connInfo.ConnectionTimeout}秒");
            Console.WriteLine($"命令超时: {connInfo.CommandTimeout}秒");
            Console.WriteLine($"连接池: {(connInfo.Pooling ? "启用" : "禁用")}");
            Console.WriteLine();
            
            // 2. 网络连通性测试
            Console.WriteLine("=== 2. 网络连通性测试 ===");
            var networkOk = await TestNetworkConnectivity(connInfo.Host, connInfo.Port);
            Console.WriteLine();
            
            // 3. DNS解析测试
            Console.WriteLine("=== 3. DNS解析测试 ===");
            await TestDnsResolution(connInfo.Host);
            Console.WriteLine();
            
            // 4. Oracle连接测试
            Console.WriteLine("=== 4. Oracle连接测试 ===");
            var connectionOk = await TestOracleConnection(connectionString);
            Console.WriteLine();
            
            // 5. 连接池测试
            if (connectionOk)
            {
                Console.WriteLine("=== 5. 连接池压力测试 ===");
                await TestConnectionPool(connectionString);
                Console.WriteLine();
            }
            
            // 6. 性能基准测试
            if (connectionOk)
            {
                Console.WriteLine("=== 6. 性能基准测试 ===");
                await PerformanceBenchmark(connectionString);
                Console.WriteLine();
            }
            
            // 7. 生成诊断报告
            Console.WriteLine("=== 7. 诊断总结 ===");
            Console.WriteLine($"网络连通性: {(networkOk ? "✓ 正常" : "❌ 异常")}");
            Console.WriteLine($"Oracle连接: {(connectionOk ? "✓ 正常" : "❌ 异常")}");
            
            if (!networkOk)
            {
                Console.WriteLine("\n🔧 网络问题解决建议:");
                Console.WriteLine("• 检查防火墙设置，确保端口开放");
                Console.WriteLine("• 验证Oracle服务器是否运行");
                Console.WriteLine("• 检查网络路由和DMZ配置");
                Console.WriteLine("• 联系网络管理员确认网络策略");
            }
            
            if (networkOk && !connectionOk)
            {
                Console.WriteLine("\n🔧 Oracle连接问题解决建议:");
                Console.WriteLine("• 验证用户名和密码");
                Console.WriteLine("• 检查Oracle服务名是否正确");
                Console.WriteLine("• 增加连接超时时间");
                Console.WriteLine("• 检查Oracle监听器配置");
                Console.WriteLine("• 验证Oracle用户权限");
            }
            
            return networkOk && connectionOk;
        }
        
        private async Task<bool> TestNetworkConnectivity(string host, int port)
        {
            try
            {
                Console.WriteLine($"测试TCP连接: {host}:{port}");
                
                using (var tcpClient = new TcpClient())
                {
                    var connectTask = tcpClient.ConnectAsync(host, port);
                    var timeoutTask = Task.Delay(10000); // 10秒超时
                    
                    var completedTask = await Task.WhenAny(connectTask, timeoutTask);
                    
                    if (completedTask == connectTask && tcpClient.Connected)
                    {
                        Console.WriteLine("✓ TCP连接成功");
                        return true;
                    }
                    else
                    {
                        Console.WriteLine("❌ TCP连接失败或超时");
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 网络连接异常: {ex.Message}");
                return false;
            }
        }
        
        private async Task TestDnsResolution(string host)
        {
            try
            {
                Console.WriteLine($"DNS解析测试: {host}");
                var ping = new Ping();
                var reply = await ping.SendPingAsync(host, 5000);
                
                if (reply.Status == IPStatus.Success)
                {
                    Console.WriteLine($"✓ DNS解析成功: {reply.Address}");
                    Console.WriteLine($"延迟: {reply.RoundtripTime}ms");
                }
                else
                {
                    Console.WriteLine($"❌ Ping失败: {reply.Status}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ DNS解析异常: {ex.Message}");
            }
        }
        
        private async Task<bool> TestOracleConnection(string connectionString)
        {
            try
            {
                Console.WriteLine("测试Oracle数据库连接...");
                var stopwatch = Stopwatch.StartNew();
                
                using (var connection = new OracleConnection(connectionString))
                {
                    await connection.OpenAsync();
                    stopwatch.Stop();
                    
                    Console.WriteLine($"✓ Oracle连接成功! 耗时: {stopwatch.ElapsedMilliseconds}ms");
                    Console.WriteLine($"服务器版本: {connection.ServerVersion}");
                    Console.WriteLine($"数据库名称: {connection.DatabaseName}");
                    Console.WriteLine($"连接状态: {connection.State}");
                    
                    // 测试简单查询
                    using (var command = new OracleCommand("SELECT SYSDATE, USER FROM DUAL", connection))
                    {
                        using (var reader = await command.ExecuteReaderAsync())
                        {
                            if (await reader.ReadAsync())
                            {
                                Console.WriteLine($"服务器时间: {reader[0]}");
                                Console.WriteLine($"当前用户: {reader[1]}");
                            }
                        }
                    }
                    
                    return true;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ Oracle连接失败: {ex.Message}");
                if (ex.InnerException != null)
                {
                    Console.WriteLine($"内部错误: {ex.InnerException.Message}");
                }
                return false;
            }
        }
        
        private async Task TestConnectionPool(string connectionString)
        {
            const int poolSize = 10;
            var tasks = new Task[poolSize];
            var successCount = 0;
            
            Console.WriteLine($"测试连接池 ({poolSize}个并发连接)...");
            
            for (int i = 0; i < poolSize; i++)
            {
                int index = i;
                tasks[i] = Task.Run(async () =>
                {
                    try
                    {
                        using (var connection = new OracleConnection(connectionString))
                        {
                            await connection.OpenAsync();
                            using (var command = new OracleCommand("SELECT 1 FROM DUAL", connection))
                            {
                                await command.ExecuteScalarAsync();
                            }
                        }
                        Interlocked.Increment(ref successCount);
                        Console.Write(".");
                    }
                    catch
                    {
                        Console.Write("X");
                    }
                });
            }
            
            await Task.WhenAll(tasks);
            Console.WriteLine();
            Console.WriteLine($"连接池测试结果: {successCount}/{poolSize} 成功");
        }
        
        private async Task PerformanceBenchmark(string connectionString)
        {
            const int iterations = 20;
            var times = new List<long>();
            
            Console.WriteLine($"性能基准测试 ({iterations}次连接)...");
            
            for (int i = 0; i < iterations; i++)
            {
                try
                {
                    var stopwatch = Stopwatch.StartNew();
                    
                    using (var connection = new OracleConnection(connectionString))
                    {
                        await connection.OpenAsync();
                        using (var command = new OracleCommand("SELECT SYSDATE FROM DUAL", connection))
                        {
                            await command.ExecuteScalarAsync();
                        }
                    }
                    
                    stopwatch.Stop();
                    times.Add(stopwatch.ElapsedMilliseconds);
                    Console.Write(".");
                }
                catch
                {
                    Console.Write("X");
                }
            }
            
            Console.WriteLine();
            
            if (times.Count > 0)
            {
                var avgTime = times.Average();
                var minTime = times.Min();
                var maxTime = times.Max();
                
                Console.WriteLine($"平均响应时间: {avgTime:F2}ms");
                Console.WriteLine($"最快响应时间: {minTime}ms");
                Console.WriteLine($"最慢响应时间: {maxTime}ms");
                Console.WriteLine($"成功率: {(double)times.Count / iterations * 100:F1}%");
            }
        }
        
        private (string Host, int Port, string Service, string User, int ConnectionTimeout, int CommandTimeout, bool Pooling) ParseConnectionString(string connectionString)
        {
            var host = "未知";
            var port = 1521;
            var service = "未知";
            var user = "未知";
            var connectionTimeout = 30;
            var commandTimeout = 30;
            var pooling = true;
            
            // 解析Data Source
            var dataSourceMatch = System.Text.RegularExpressions.Regex.Match(connectionString, @"Data Source=([^:]+):?(\d+)?[/:]?([^;]+)?", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            if (dataSourceMatch.Success)
            {
                host = dataSourceMatch.Groups[1].Value;
                if (dataSourceMatch.Groups[2].Success)
                    int.TryParse(dataSourceMatch.Groups[2].Value, out port);
                if (dataSourceMatch.Groups[3].Success)
                    service = dataSourceMatch.Groups[3].Value;
            }
            
            // 解析User Id
            var userMatch = System.Text.RegularExpressions.Regex.Match(connectionString, @"User Id=([^;]+)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            if (userMatch.Success)
                user = userMatch.Groups[1].Value;
            
            // 解析Connection Timeout
            var connTimeoutMatch = System.Text.RegularExpressions.Regex.Match(connectionString, @"Connection Timeout=(\d+)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            if (connTimeoutMatch.Success)
                int.TryParse(connTimeoutMatch.Groups[1].Value, out connectionTimeout);
            
            // 解析Command Timeout
            var cmdTimeoutMatch = System.Text.RegularExpressions.Regex.Match(connectionString, @"Command Timeout=(\d+)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            if (cmdTimeoutMatch.Success)
                int.TryParse(cmdTimeoutMatch.Groups[1].Value, out commandTimeout);
            
            // 解析Pooling
            var poolingMatch = System.Text.RegularExpressions.Regex.Match(connectionString, @"Pooling=(true|false)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            if (poolingMatch.Success)
                bool.TryParse(poolingMatch.Groups[1].Value, out pooling);
            
            return (host, port, service, user, connectionTimeout, commandTimeout, pooling);
        }
    }
}
'@

$advancedTestFile = "AdvancedOracleConnectionDiagnostic.cs"
Set-Content $advancedTestFile $advancedTestContent -Encoding UTF8
Write-Host "已创建高级诊断工具: $advancedTestFile" -ForegroundColor Green

# 第四步：创建连接重试增强器
Write-Host "
=== 第四步：创建连接重试增强器 ===" -ForegroundColor Cyan

$retryEnhancerContent = @'
using Oracle.ManagedDataAccess.Client;
using System;
using System.Threading.Tasks;
using System.Threading;

namespace Lzfy_His_Service
{
    /// <summary>
    /// DMZ环境Oracle连接重试增强器
    /// 专门处理网络不稳定环境下的连接问题
    /// </summary>
    public class DmzOracleConnectionEnhancer
    {
        private readonly string _connectionString;
        private readonly int _maxRetries;
        private readonly TimeSpan _baseDelay;
        
        public DmzOracleConnectionEnhancer(string connectionString, int maxRetries = 5, TimeSpan? baseDelay = null)
        {
            _connectionString = connectionString;
            _maxRetries = maxRetries;
            _baseDelay = baseDelay ?? TimeSpan.FromSeconds(2);
        }
        
        /// <summary>
        /// 创建具有增强重试机制的Oracle连接
        /// </summary>
        public async Task<OracleConnection> CreateConnectionAsync(CancellationToken cancellationToken = default)
        {
            var attempt = 0;
            Exception lastException = null;
            
            while (attempt < _maxRetries)
            {
                try
                {
                    var connection = new OracleConnection(_connectionString);
                    
                    // 使用超时控制的连接打开
                    using (var timeoutCts = new CancellationTokenSource(TimeSpan.FromSeconds(120)))
                    using (var combinedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCts.Token))
                    {
                        await connection.OpenAsync(combinedCts.Token);
                    }
                    
                    // 验证连接
                    await ValidateConnectionAsync(connection, cancellationToken);
                    
                    Console.WriteLine($"Oracle连接成功 (尝试 {attempt + 1}/{_maxRetries})");
                    return connection;
                }
                catch (Exception ex) when (IsRetriableException(ex))
                {
                    lastException = ex;
                    attempt++;
                    
                    if (attempt < _maxRetries)
                    {
                        var delay = CalculateDelay(attempt);
                        Console.WriteLine($"连接失败 (尝试 {attempt}/{_maxRetries}): {ex.Message}");
                        Console.WriteLine($"等待 {delay.TotalSeconds:F1} 秒后重试...");
                        
                        await Task.Delay(delay, cancellationToken);
                    }
                }
                catch (Exception ex)
                {
                    // 非可重试异常，直接抛出
                    Console.WriteLine($"Oracle连接失败 (不可重试): {ex.Message}");
                    throw;
                }
            }
            
            throw new InvalidOperationException(
                $"Oracle连接失败，已重试 {_maxRetries} 次。最后错误: {lastException?.Message}", 
                lastException);
        }
        
        /// <summary>
        /// 执行带重试的Oracle命令
        /// </summary>
        public async Task<T> ExecuteWithRetryAsync<T>(Func<OracleConnection, Task<T>> operation, CancellationToken cancellationToken = default)
        {
            using (var connection = await CreateConnectionAsync(cancellationToken))
            {
                return await ExecuteOperationWithRetry(connection, operation, cancellationToken);
            }
        }
        
        private async Task<T> ExecuteOperationWithRetry<T>(OracleConnection connection, Func<OracleConnection, Task<T>> operation, CancellationToken cancellationToken)
        {
            var attempt = 0;
            Exception lastException = null;
            
            while (attempt < _maxRetries)
            {
                try
                {
                    // 检查连接状态
                    if (connection.State != System.Data.ConnectionState.Open)
                    {
                        await connection.OpenAsync(cancellationToken);
                    }
                    
                    return await operation(connection);
                }
                catch (Exception ex) when (IsRetriableException(ex))
                {
                    lastException = ex;
                    attempt++;
                    
                    if (attempt < _maxRetries)
                    {
                        var delay = CalculateDelay(attempt);
                        Console.WriteLine($"操作失败 (尝试 {attempt}/{_maxRetries}): {ex.Message}");
                        Console.WriteLine($"等待 {delay.TotalSeconds:F1} 秒后重试...");
                        
                        // 尝试重新连接
                        try
                        {
                            if (connection.State == System.Data.ConnectionState.Open)
                            {
                                connection.Close();
                            }
                            await Task.Delay(delay, cancellationToken);
                            await connection.OpenAsync(cancellationToken);
                        }
                        catch
                        {
                            // 重连失败，继续重试
                        }
                    }
                }
            }
            
            throw new InvalidOperationException(
                $"Oracle操作失败，已重试 {_maxRetries} 次。最后错误: {lastException?.Message}", 
                lastException);
        }
        
        private async Task ValidateConnectionAsync(OracleConnection connection, CancellationToken cancellationToken)
        {
            using (var command = new OracleCommand("SELECT 1 FROM DUAL", connection))
            {
                command.CommandTimeout = 30;
                await command.ExecuteScalarAsync(cancellationToken);
            }
        }
        
        private bool IsRetriableException(Exception ex)
        {
            // Oracle特定的可重试错误
            if (ex is OracleException oracleEx)
            {
                return oracleEx.Number switch
                {
                    12170 => true, // TNS: 连接超时
                    12171 => true, // TNS: 无法解析连接描述符
                    12541 => true, // TNS: 无监听程序
                    12543 => true, // TNS: 目标主机或对象不存在
                    12545 => true, // 因目标主机或对象不存在，连接失败
                    12547 => true, // TNS: 连接丢失
                    12560 => true, // TNS: 协议适配器错误
                    12571 => true, // TNS: 包写入失败
                    12609 => true, // TNS: 操作超时
                    3113 => true,  // 通信通道的文件结尾
                    3114 => true,  // 未连接到ORACLE
                    1033 => true,  // ORACLE正在初始化或关闭
                    1034 => true,  // ORACLE不可用
                    1089 => true,  // 立即关闭正在进行
                    17002 => true, // IO异常
                    _ => false
                };
            }
            
            // 网络相关异常
            return ex is System.Net.Sockets.SocketException ||
                   ex is System.TimeoutException ||
                   ex is TaskCanceledException ||
                   ex.Message.Contains("timeout", StringComparison.OrdinalIgnoreCase) ||
                   ex.Message.Contains("network", StringComparison.OrdinalIgnoreCase);
        }
        
        private TimeSpan CalculateDelay(int attempt)
        {
            // 指数退避算法，但有最大限制
            var delay = TimeSpan.FromMilliseconds(_baseDelay.TotalMilliseconds * Math.Pow(2, attempt - 1));
            return delay > TimeSpan.FromSeconds(30) ? TimeSpan.FromSeconds(30) : delay;
        }
    }
}
'@

$retryEnhancerFile = "DmzOracleConnectionEnhancer.cs"
Set-Content $retryEnhancerFile $retryEnhancerContent -Encoding UTF8
Write-Host "已创建连接重试增强器: $retryEnhancerFile" -ForegroundColor Green

# 第五步：编译项目
Write-Host "
=== 第五步：编译项目 ===" -ForegroundColor Cyan
try {
    $buildResult = dotnet build --configuration Release
    if ($LASTEXITCODE -eq 0) {
        Write-Host "✓ 项目编译成功!" -ForegroundColor Green
    } else {
        Write-Host "⚠ 项目编译可能有问题，请检查" -ForegroundColor Yellow
    }
} catch {
    Write-Host "编译过程中出现错误: $_" -ForegroundColor Yellow
}

# 显示解决方案总结
Write-Host "
" -ForegroundColor White
Write-Host "=== DMZ环境Oracle连接问题终极解决方案完成 ===" -ForegroundColor Green
Write-Host "✓ 已创建高级连接诊断工具" -ForegroundColor Green
Write-Host "✓ 已创建DMZ环境连接重试增强器" -ForegroundColor Green
Write-Host "✓ 已优化连接字符串参数" -ForegroundColor Green
Write-Host "✓ 项目编译完成" -ForegroundColor Green

Write-Host "
=== 解决方案特点 ===" -ForegroundColor Cyan
Write-Host "• 使用Oracle.ManagedDataAccess.Core纯托管驱动" -ForegroundColor White
Write-Host "• 无需Oracle客户端安装" -ForegroundColor White
Write-Host "• 智能重试机制，适应网络不稳定" -ForegroundColor White
Write-Host "• 全面的连接诊断功能" -ForegroundColor White
Write-Host "• 针对DMZ环境优化的连接参数" -ForegroundColor White
Write-Host "• 指数退避重试算法" -ForegroundColor White

Write-Host "
=== 使用方法 ===" -ForegroundColor Yellow
Write-Host "1. 运行诊断工具:" -ForegroundColor White
Write-Host "   var diagnostic = new AdvancedOracleConnectionDiagnostic(configuration);" -ForegroundColor Gray
Write-Host "   await diagnostic.ComprehensiveDiagnosticAsync();" -ForegroundColor Gray
Write-Host "" -ForegroundColor White
Write-Host "2. 使用增强连接器:" -ForegroundColor White
Write-Host "   var enhancer = new DmzOracleConnectionEnhancer(connectionString);" -ForegroundColor Gray
Write-Host "   using var connection = await enhancer.CreateConnectionAsync();" -ForegroundColor Gray
Write-Host "" -ForegroundColor White
Write-Host "3. 执行带重试的操作:" -ForegroundColor White
Write-Host "   var result = await enhancer.ExecuteWithRetryAsync(async conn => {" -ForegroundColor Gray
Write-Host "       // 您的数据库操作" -ForegroundColor Gray
Write-Host "   });" -ForegroundColor Gray

Write-Host "
=== 关键优势 ===" -ForegroundColor Cyan
Write-Host "• 解决DMZ环境网络不稳定问题" -ForegroundColor White
Write-Host "• 智能识别可重试的Oracle错误" -ForegroundColor White
Write-Host "• 自动连接恢复和验证" -ForegroundColor White
Write-Host "• 详细的诊断和监控信息" -ForegroundColor White
Write-Host "• 生产环境可靠性保证" -ForegroundColor White

Write-Host "
这是针对DMZ环境Oracle连接问题的终极解决方案!" -ForegroundColor Green
Write-Host "如果仍有问题，请运行诊断工具获取详细信息。" -ForegroundColor Yellow